const app = getApp();
const https = require('../../utils/https');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    checkItems: [],
    email: '',
    order_status: '',
    source_list: [],
    source_index: null,
    maskShow2: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log(options.inspector_id)
    if (options && options.order_id != '') {
      that.setData({
        order_sn: options.order_sn,
        order_id: options.order_id,
        inspector_id: options.inspector_id,
        order_status: options.status
      })
    }
    this.getReportInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getCheckResult(this.data.order_id)
    const bool = this.getSourceFormStatus(this.data.order_id);
    if(!bool) {
      this.getSourceList().then(res => {
        this.setData({
          source_list: res,
          maskShow2: true
        })
      })
    }
  },
  //获取用户来源列表
  getSourceList() {
    var that = this;
    return new Promise((success, fail) => {
      https.post('getSource', null, false, '').then(res => {
        success(res)
      }).catch(() => {
        fail()
      })
    })

  },
  /* 获取验房项目
* @param orderId 订单id
   */
  getCheckResult() {
    const {order_id, inspector_id} = this.data
    wx.request({
      url: 'https://wx.amagich.com/' + 'v1/' + 'getCheckResultV02',
      data: {
        inspector_id,
        order_id,
      },
      header: {
        "Content-Type": "application/json"
      },
      method: 'GET',
      success: res => {
        console.log(res.data.resultData)
        const checkItems = res.data.resultData;
        checkItems[0].expend = true
        this.setData({
          checkItems
        })
      }})
  },
  /* 获取验房项目
  * @param orderId 订单id
      */
  getBookOrderItems(orderId) {
  wx.request({
    url: 'https://wx.amagich.com/' + 'v1/' + 'getBookOrderItems',
    data: {
      id: orderId,
    },
    header: {
      "Content-Type": "application/json"
    },
    method: 'GET',
    success: res => {
      console.log(res.data.resultData)
      this.setData({
        checkItems: res.data.resultData
      })
    }})
},
  /**
   * @xk 获取生成报告的相关信息
   * @param {} res
   */
  getReportInfo: function (res) {
    var that = this,
      order_sn = this.data.order_sn;
    https.post('getReportView', {
      order_sn: order_sn
    }, true, '加载中').then(res => {
      that.setData({
        report_txt_num: res.reportTextNum,
        check_time: res.check_time,
        inspector_name: res.inspector_name,
        house_register: res.house_register,
        check_end_time: res.check_end_time,
        position_list: res.position_list,
        check_by: res.check_by,
        app_name: res.app_name,
        tel: res.tel,
        app_ewm: res.app_ewm,
        report_link: res.report_link,
        kh: res.kh
      })
    })
  },
  downloadReport: function () {
    var that = this;
    const {order_sn, report_link, order_status} = this.data;
    // order_id=274&inspector_id=6&order_sn=202101130951330020&status=5
  
    // if(order_status === '5') {
    //   wx.showModal({
    //     title: '提示',
    //     content: '填写评论，评论选中立返五元',
    //     success (res) {
    //       if (res.confirm) {
    //         console.log('用户点击确定')
    //         wx.redirectTo({
    //           url: `/pages/evaluate2/?order_sn=${order_sn}`,
    //         })
    //       } else if (res.cancel) {
    //         console.log('用户点击取消')
    //       }
    //     }
    //   })
    //   return
    // }
  
    const downloadTask = wx.downloadFile({
      url: report_link,
      // filePath: wx.env.USER_DATA_PATH + "/"+order_sn+".pdf",
      success(res) {
        console.log(res)
        const tempFilePath = res.tempFilePath
        if (res.statusCode === 200) {                     //成功
          var Path = res.tempFilePath                     //返回的文件临时地址，用于后面打开本地预览所用
          wx.openDocument({
            filePath: Path,                               //要打开的文件路径
            success: function (res) {
              console.log('打开PDF成功');
            },
            fail(res) {
              console.log(res)
            }
          })
          // wx.saveFile({
          //   tempFilePath,
          //   success (res2) {
          //     console.log(res2)
          //     const savedFilePath = res2.savedFilePath
          //     wx.getSavedFileInfo({
          //       filePath:savedFilePath,
          //       success(res3) {
          //         console.log(res3)
          //       }
          //     })
          //     wx.showModal({
          //       title: '文件已保存到手机',
          //       content: '文件路径'+ savedFilePath,
          //       confirmColor: '#0bc183',
          //       confirmText: '知道了',
          //       showCancel: false
          //     })
          //   }
          // })

        }
      },
      fail(res) {
        console.log(res)
      }
    })
    downloadTask.onProgressUpdate((res) => {
      if (res.progress >= 100) {
        wx.hideLoading({
          success: (res) => {},
        })
      } else {
        wx.showLoading({
          title: '已下载' + res.progress + '%',
        })
      }
    })
  },
  expendItem(e) {
    const index = e.currentTarget.dataset.index;
    const checkItems = JSON.parse(JSON.stringify(this.data.checkItems))
    checkItems[index].expend = !checkItems[index].expend
    this.setData({
      checkItems
    })
  },
    // 发送邮箱
    emailTap(){
      this.setData({
        maskShow: true,
        emailShow: true
      })
    },
    qxEmail(){
      this.setData({
        maskShow: false,
        emailShow: false
      })
    },
    chanageEmail: function(Obj){
      this.setData({email: Obj.detail.value});
    },
    sureEmail(e){
      var that = this,
          order_sn = this.data.order_sn,
          email = this.data.email;
      if(email == ''){
        wx.showToast({
          title: '请填写收件人邮箱',
          icon: 'none',
          duration: 1500
        })
        return false;
      }
      wx.showLoading({
        title: '正在发送邮件',
      })
      https.post('sendEmail',{order_sn: order_sn,email: email},false,'正在发送邮件').then(res=>{
        if(res){
          wx.hideLoading({
            success: (res) => {},
          })
          wx.showToast({
            title: '验房报告正在送达，请注意查收',
            icon: 'none',
            duration: 1500
          })
          that.setData({
            maskShow: false,
            emailShow: false
          })
        }
      })
    },

  // 获取本地存储
  getSourceFormStatus(order_id){
    return wx.getStorageSync('sourceForm_' + order_id)
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // this.onShow();
  },
  maskHide:function () {
    console.log('??')
    this.setData({
      maskShow2: false
    })
  },
  bindPickerChange(e) {
    console.log(e.detail.value)
    this.setData({
      source_index: e.detail.value
    })
  },
  //
  saveSource() {
    const {source_index, order_id} = this.data;
    if(!source_index) {
      wx.showToast({
        title: '请选择途径',
        icon: 'none',
        duration: 1500
      })
      return
    }
    this.saveSourceList().then(() => {
      console.log('1')
      wx.setStorageSync('sourceForm_' + order_id, true)
      this.maskHide()
    }).catch(() => {

    })
  },
  // 保存用户来源
  saveSourceList() {
    var that = this;
    const {order_id, source_list, source_index} = this.data;

    return new Promise((success, fail) => {
      if(!source_index) {
        wx.showToast({
          title: '请选择预约途径',
          icon: 'none',
          duration: 1500
        })
        return fail();
      }
      https.post('saveSource', {
        book_order_id: order_id,
        source_id: source_list[source_index].id
      }, false, '').then(res => {
        success()
      }).catch(() => {
        fail()
      })
    })

  },
})
